import datetime
import json
import os
from datetime import datetime
from playwright.sync_api import BrowserContext

from config.config import get_upload_dir_path
from model.ProConfModel import ProConfModel


'''
需要登录的条件
1. cookie配置文件不存在
2. cookie必要配置名称不存在
3. cookie时间过期（-1或者 0 不算过期）
4. allow_cookie 里面不重要的名字不检测
'''

def need_login(pro_config: ProConfModel) -> bool:
    path = get_act_storage_path_by_pro(pro_config)
    if not os.path.exists(path):
        return True
    try:
        with open(path, 'r') as f:
            session_data = json.load(f)

        current_time = datetime.now().timestamp()
        cookie_name_list=[]
        for cookie in session_data.get("cookies", []):
            cookie_name_list.append(cookie.get("name",""))
            if cookie["expires"] == -1 or allow_cookie(cookie) or cookie["expires"] == 0:
                continue
            if current_time > cookie["expires"]:
                return True  # 需要重新登录

        if pro_config.cookie_must_name not in cookie_name_list:
            return True

        return False

    except json.JSONDecodeError:
        print(f"会话文件格式错误: {path}")
        return True  # 需要登录
    except Exception as e:
        print(f"读取会话文件时出错: {str(e)}")
        return True  # 需要登录


def set_keep_alive_storage(pro_config: ProConfModel, context: BrowserContext):
    context.add_cookies([{
        'name': 'session_id_1919_pm',
        'value': '12345',
        'url': 'https://example.com',
        'expires': int(datetime.now().timestamp()) + pro_config.cookie_keep_time
    }])
    context.storage_state(path=get_act_storage_path_by_pro(pro_config))


def get_act_storage_path_by_pro(pro_config: ProConfModel) -> str:
    return get_upload_dir_path() + pro_config.server_name + ".json"


def get_storage_path_by_pro(pro_config: ProConfModel):
    """根据配置获取对应的存储路径，存在返回路径，否则返回None"""
    # 构建完整文件路径
    full_path = get_act_storage_path_by_pro(pro_config)

    # 检查文件是否存在
    if os.path.exists(full_path):
        return full_path
    return None


def allow_cookie (cookie):
    name=cookie.get("name", "")
   # if "gr_session_id" in name or "acw_tc" in name or "cdn_sec_tc" in name:
    if "gr_session_id" in name :
        return True
    return False